package com.ts.auth.service;

import com.ts.auth.feign.UserFeignClient;
import com.ts.auth.pojo.dto.userOrg.TbPermission;
import com.ts.auth.pojo.dto.userOrg.TbUser;
import com.ts.common.exception.ExceptionFactory;
import com.ts.common.pojo.resp.TResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.jaas.AuthorityGranter;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.security.Permission;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private final static String DEFAULT_ROLE_PREFIX = "ROLE_";

    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        TResponse<TbUser> userResp = userFeignClient.getByName(s);
        if (!"200".equals(userResp.getCode())) {
            ExceptionFactory.createErrorBaseException(userResp.getMsg());
        }

        TbUser user = userResp.getData();

        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        TResponse<List<TbPermission>> permissionResp = userFeignClient.getPermissionByUserId(user.getId());
        if (!"200".equals(permissionResp.getCode())) {
            ExceptionFactory.createErrorBaseException(permissionResp.getMsg());
        }

        permissionResp.getData().forEach(f -> {
            grantedAuthorities.add(new SimpleGrantedAuthority(DEFAULT_ROLE_PREFIX + f.getName()));
        });
        return new User(user.getUsername(),user.getPassword(),grantedAuthorities);
    }
}
